<template>
  <div>
    <!-- 搜索结果页-头部导航 -->
    <div class="search-result-container">
      <!-- 点击实现后退效果 -->
      <van-nav-bar
        title="搜索结果"
        left-arrow
        @click-left="$router.go(-1)"
        fixed
      />
    </div>

    <!-- 文章列表 -->
    <div>
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
        :immediate-check="false"
        offset="50"
      ></van-list>
      <ArticleItem
        v-for="obj in articleList"
        :key="obj.art_id"
        :artItem="obj"
        :isShow="false"
        @click.native="itemClickFn(obj.art_id)"
      ></ArticleItem>
    </div>
  </div>
</template>

<script>
import { searchResultAPI } from '@/api/index'
import ArticleItem from '@/components/ArticleItem'

export default {
  name: 'SearchResult',
  components: {
    ArticleItem
  },
  data () {
    return {
      // 页码
      page: 1,
      // 文章列表
      articleList: [],
      // 加载状态
      loading: false,
      // 是否全部加载完成
      finished: false
    }
  },
  async created () {
    const res = await searchResultAPI({
      page: this.page,
      q: this.$route.params.kw
    })
    this.articleList = res.data.data.results
  },
  methods: {
    async onLoad () {
      if (this.articleList.length > 0) {
        this.page++
        const res = await searchResultAPI({
          page: this.page,
          q: this.$route.params.kw
        })
        if (res.data.data.results.length === 0) {
          // 没有数据了
          this.finished = true
          return
        }
        this.articleList = [...this.articleList, ...res.data.data.results]

        this.loading = false
      }
    },
    // 跳转到详情
    itemClickFn (id) {
      this.$router.push({
        path: `/detail?art_id=${id}`
      })
    }
  }
}
</script>

<style lang="less" scoped>
.search-result-container {
  padding-top: 46px;
}
</style>
